package org.dubh.common.collect;

import com.google.common.collect.ForwardingQueue;

import java.util.concurrent.ArrayBlockingQueue;


/**
 * A <tt>BoundedQueue</tt> that will discard items when it reaches capacity.<p>
 *
 * The {@link #offer(E)} method will always add the element at the end of this
 * queue, discarding the head of the queue if necessary to make space for it.
 *
 * @author brian.duff@dubh.org
 */
public final class DiscardingBoundedQueue<E> extends ForwardingQueue<E> {
    private final int capacity;
    
    
    public DiscardingBoundedQueue( int capacity ) {
        super( new ArrayBlockingQueue<E>( capacity ) );
        this.capacity = capacity;
    }

    @Override
    public synchronized boolean offer(E object) {
        if ( size() >= capacity ) remove();
        return super.offer(object);
    }

    @Override
    public boolean add(E e) {
        if ( offer( e ) ) return true;
        throw new IllegalStateException( "Queue full" );
    }
    
// Override methods that modify the queue to make sure they are locked with
// the same lock we use in offer.

    @Override
    public synchronized void clear() {
        super.clear();
    }

    @Override
    public synchronized E remove() {
        return super.remove();
    }


}
